package com.wohuijituan.whcsmerchant.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.activity.GoodsCompileActivity;
import com.wohuijituan.whcsmerchant.adapter.GoodsAddAdapter;
import com.wohuijituan.whcsmerchant.bean.GoodsAddListBean;
import com.wohuijituan.whcsmerchant.callback.GoodsAddListCallBack;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.ExtraName;
import com.wohuijituan.whcsmerchant.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by zsy_18 on 2017/1/18.
 */

public class SystemGoodsSearchFragment extends MyBaseFragment implements View.OnClickListener {
    public static SystemGoodsSearchFragment newInstance(String cateID, String cateName) {
        SystemGoodsSearchFragment fragment = new SystemGoodsSearchFragment();
        Bundle data = new Bundle();
        data.putString("cateID", cateID);
        data.putString("cateName", cateName);
        fragment.setArguments(data);
        return fragment;
    }

    public static final String TAG = "SystemGoodsSearchFragment";
    private PullToRefreshListView pullGoodsList;
    private String cateID;
    private String cateName;
    private GoodsAddAdapter myAdapter;
    private List<GoodsAddListBean.DataEntity.GoodsEntity> goodsList;
    private int nowPage = 1;//当前显示页数
    private int totalPage;//订单总页数
    private int pageNumber = 10;//每页显示个数
    private String keyWord = "";//搜索的关键字

    @Override
    protected View createMyView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_goods_list, container, false);
        iniView(v);
        initData();
        initListener();
        return v;
    }

    private void iniView(View v) {
        pullGoodsList = (PullToRefreshListView) v.findViewById(R.id.pull_goods_list);
        pullGoodsList.setMode(PullToRefreshBase.Mode.BOTH);
    }

    private void initData() {
        cateID = getArguments().getString("cateID");
        cateName = getArguments().getString("cateName");
        goodsList = new ArrayList<>();
        myAdapter = new GoodsAddAdapter(ctx, goodsList);
        pullGoodsList.setAdapter(myAdapter);
    }

    private void initListener() {
        myAdapter.setMyOnItemBtnClickListener(new GoodsAddAdapter.MyOnItemBtnClickListener() {
            @Override
            public void onClick(int position, View view) {
                Intent intent = new Intent(ctx, GoodsCompileActivity.class);
                GoodsAddListBean.DataEntity.GoodsEntity data = goodsList.get(position);
                intent.putExtra(ExtraName.GOODSADD_BEAN, data);
                intent.putExtra(ExtraName.TAG, GoodsAddFragment.TAG);
                startActivity(intent);
            }
        });
        pullGoodsList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                searchGoodsRequest(keyWord,cateID,1,pageNumber);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (nowPage < totalPage) {
                    //得到下一页数据
                    searchGoodsRequest(keyWord,cateID,nowPage+1,pageNumber);
                } else {
                    showToast(ctx, "已经是最后一页");
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            pullGoodsList.onRefreshComplete();
                        }
                    }, 500);

                }

            }
        });
    }

    private static final int GoodsAddList_OK = 140;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GoodsAddList_OK:
                    GoodsAddListBean bean = (GoodsAddListBean) msg.obj;
                    nowPage = bean.getData().getPageIndex();
                    totalPage = bean.getData().getPageCount();
                    if (nowPage == 1) {
                        myAdapter.replace(bean.getData().getData());
                        LogUtils.e(TAG, nowPage + "数据个数:" + bean.getData().getData().size());
                    } else if (nowPage > 1) {
//                        myAdapter.addAll(bean.getData().getData());
                        goodsList.addAll(bean.getData().getData());
                        myAdapter.notifyDataSetChanged();
                    }
                    dismissDialog();
                    break;
            }

        }
    };
    /**
     * 进行搜索,public方法,外部调用
     * @param keyWord
     */
    public void doSearchGoods(String keyWord){
        this.keyWord = keyWord;
        searchGoodsRequest(keyWord,cateID,1,pageNumber);
    }
    /**
     * 搜索商品的网络请求
     * @param keyWord
     */
    private void searchGoodsRequest(String keyWord,String cateID,int pageIndex,int rows){
        showDialog(ctx);
        params.clear();
        String strUrl = Urls.SystemShopSearch;
        params.addStringRequest(ParamsKey.UserKey,myApplication.getUserKey());
        params.addStringRequest(ParamsKey.SystemGoodsSearch_KeyWord,keyWord);
        params.addStringRequest(ParamsKey.SystemGoodsSearch_CateID,cateID);
        params.addStringRequest(ParamsKey.SystemGoodsSearch_PageIndex,pageIndex+"");
        params.addStringRequest(ParamsKey.SystemGoodsSearch_Rows,rows+"");
        myOkHttpUtils.postRequest(strUrl, params, new GoodsAddListCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
                pullGoodsList.onRefreshComplete();
            }
            @Override
            public void onResponse(GoodsAddListBean response, int id) {
                if (response.getState() == 1) {
                    Message msg = new Message();
                    msg.what = GoodsAddList_OK;
                    msg.obj = response;
                    handler.sendMessage(msg);
                } else if (response.getState() == 0) {
                    showToast(ctx, "服务器数据为空");
                } else {
                    showToast(ctx, response.getMsg());
                    dismissDialog();
                }
                pullGoodsList.onRefreshComplete();
            }
        });
    }
    @Override
    public void onClick(View v) {

    }
}
